<template>
  <div style="display: flex;flex-wrap: wrap">
    <div v-for="(item,index) in $store.state.detailsVideoList" :key="index" v-if="showFlag" style="margin-right: 5px;">
      <div style="display: flex">
        <div v-if="!isBlank(item.videoCover)" class="demo-upload-list">
          <div class="demo-upload-list-cover">
            <img class="avatarCopy" :src="imageUtils('videoTest/',item.videoCover)">
            <el-icon class="el-icon-zoom-in"
                     @click.native="handlePictureCardPreview(coverOneUrl)"/>
            <el-icon class="el-icon-delete-solid" @click.native="handleRemove()"/>
          </div>
        </div>
      </div>
    </div>
    <el-upload
      action="#"
      accept=".mp4"
      list-type="picture-card"
      :show-file-list="false"
      :on-change="beforeUpload"
      :auto-upload="false">
      <i slot="default" class="el-icon-plus" style="position: absolute;left: 33%;top: 30%;"></i>
    </el-upload>
  </div>
</template>

<script>
import store from "@/store/index";
import appUtils, {isBlank, initCacheData, isFlag, videoListOssUpload} from "@/utils/util";
import {imageUtils} from "@/utils/imageUtil";

export default {
  props: ["imgUrl", "maxNumber", 'fileSize'],
  name: "detailsVideoUpload",
  data() {
    return {
      showFlag: true,
      uploadFlag: false,
      detailsVideoList: [
        {
          videoCover: ''
        }
      ],
      colors: [
        {color: '#909399', percentage: 25},
        {color: '#e6a23c', percentage: 50},
        {color: '#409eff', percentage: 75},
        {color: '#67c23a', percentage: 100}
      ],
    }
  },
  methods: {
    isFlag,
    imageUtils,
    isBlank,
    handlePictureCardPreview(){

    },
    handleRemove(){

    },
    beforeUpload(file) {
      console.log(file)
      var fileSize = 10
      var maxNumber = 3
      if (!isBlank(this.fileSize)) {
        fileSize = this.fileSize
      }
      if (!isBlank(this.maxNumber)) {
        maxNumber = this.maxNumber
      }
      this.handleMaxSize(file, fileSize).then(res => {
        if (isFlag(res, true)) {
          new Promise(resolve => {
            this.findVideoPoster(file).then(res => {
              console.log("转化封面", file)
              file.videoCover = res
              resolve(file)
            })
          }).then(res => {
            if (!isBlank(res)) {
              if (store.state.detailsVideoList.length < maxNumber) {
                store.state.detailsVideoList.push(res)
              } else {
                store.state.detailsVideoList.splice(maxNumber - 1, 1, res)
              }
              console.log("处理结果", store.state.detailsVideoList)
              this.showFlag = false
              this.showFlag = true
            }
          })
        }
      })
    },
    beforeAvatarUpload(file, fileList, index) {
      console.log(index)
    },
    //限定文件最大
    handleMaxSize(file, size) {
      const fileSize = file.size / 1024 / 1024 < size
      return new Promise((resolve, reject) => {
        if (!fileSize) {
          this.$notify.error({
            title: '文件过大',
            message: '请不要超过' + size + 'MB.'
          })
          return resolve(false)
        } else {
          return resolve(true)
        }
      })
    },
    hanleDeleteItem(param, index) {
      store.state.detailsVideoList.splice(index, 1)
      console.log(store.state.detailsVideoList)
    },
    handleUpload() {
      store.state.detailsVideoList.forEach((file, index) => {
        if (!isFlag(file.percentage, 100) || isBlank(file.percentage)) {
          new Promise((resolve) => {
            videoListOssUpload(this.imgUrl, file, index)
            setTimeout(() => {
              resolve(true)
            }, 500)
          }).then((res) => {
            console.log(res)
            setTimeout(() => {
              this.findVideoPoster(file).then(res => {
                file.videoCover = res
                this.showFlag = false
                this.showFlag = true
              })
            }, 300)
          })
        }
      })
    },
    handleView(param) {
      window.open(appUtils.myImage + this.imgUrl + param.fileName)
    },
    findVideoPoster(param) {
      var file = param.raw
      let self = this
      return new Promise(function (resolve) {
        let base64URL = ''
        let video = document.createElement('video')
        video.setAttribute('crossOrigin', 'anonymous') //处理跨域
        video.setAttribute('src', URL.createObjectURL(file))
        video.currentTime = 1
        video.addEventListener('loadeddata', function () {
          let canvas = document.createElement('canvas')
          //使用视频的宽高作为canvas、预览图的宽高
          let width = video.videoWidth
          let height = video.videoHeight
          canvas.width = width
          canvas.height = height
          canvas.getContext('2d').drawImage(video, 0, 0, width, height) //绘制canvas
          base64URL = canvas.toDataURL('image/jpeg') //转换为base64，图片格式默认为png，这里修改为jpeg
          let fileName = String(new Date().getTime()) + parseInt(Math.random() * 100000) + '.jpeg'
          // let fileNew = self.convertFile(base64URL, fileName)
          // let fileName1 = ossPut(fileNew, 'videoTest/')
          resolve(base64URL)
        })
      })
    },
    convertFile(base64, fileName) {
      console.log(fileName)
      let fileArray = base64.split(','),
        fileType = fileArray[0].match(/:(.*?);/)[1],
        bstr = atob(fileArray[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], fileName, {type: fileType})
    },
  }
}
</script>

<style scoped>
/deep/ .el-upload el-upload--text {
  width: 85px;
  height: 85px;
}
/deep/ .el-upload-list--picture-card .el-upload-list__item {
  width: 85px;
  height: 85px;
}
/deep/ .el-upload--picture-card  {
  position: relative;
  width: 85px;
  height: 85px;
}
/deep/ .demo-upload-list:hover .demo-upload-list-cover  {
  display: none;
}
/deep/ .demo-upload-list-cover  {
  display: block;
}
</style>
